package com.lwl.blog.filter;


import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(filterName = "EncodingFilter",
        urlPatterns = {"/PageServlet/*","/SystemUserServlet/*","/IndexServlet/*","/UserServlet/*"},
        initParams = {@WebInitParam(name = "encoding", value = "utf-8")
})
public class EncodingFilter implements Filter {
    private String encoding;
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        //类型转换
        HttpServletRequest request= (HttpServletRequest) req;
        HttpServletResponse response=(HttpServletResponse)resp;

        // 2.设置编码
        req.setCharacterEncoding(encoding); // 读取内容的时候使用utf-8去读
//        resp.setContentType("text/html;charset=" + encoding); // 设置响应的内容编码
        resp.setCharacterEncoding("utf-8");
        //放行
        chain.doFilter(request, response);
    }

    public void init(FilterConfig config) throws ServletException {
        encoding=config.getInitParameter("encoding");

    }

}
